﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace meituan
{
    class Utils
    {
        public static Dictionary<string, string> getCityList()
        {
            Dictionary<string, string> city = new Dictionary<string, string>();
            string jsonText = Properties.Resources.city;
            JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
            foreach (JArray i in jo["openCityList"])
            {
                foreach (JObject ii in i[1])
                {
                    city.Add(ii["name"].ToString(), ii["id"].ToString());
                }
            }
            return city;
        }

        public static Dictionary<string, string> getCityLinkList()
        {
            string jsonText = Properties.Resources.cityLink;
            Dictionary<string, string> cityLink = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonText);
            return cityLink;
        }

        public static Dictionary<string, string> getConfig()
        {
            string tempPath = Utils.TempPath("meituan_config");
            if (File.Exists(tempPath))
            {
                string str = File.ReadAllText(tempPath);
                Dictionary<string, string> config = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
                return config;
            }
            return null;
        }

        /*public static void GetDianpu(Dictionary<string, string> config, string referer, string cityid, string dianpu, string diqu)
        {
            int limit = 32;
            int offset = 0;
            while (true)
            {
                string url = $"https://apimobile.meituan.com/group/v4/poi/pcsearch/{cityid}?uuid=a2057b227096495383a6.157611380.1.0.0&limit={limit}&offset={offset}&cateId=-1&q={dianpu}";
                string res = HttpGet(url, referer);
                JObject jo = (JObject)JsonConvert.DeserializeObject(res);
                //var total = jo["data"]["totalCount"];
                string fileName = diqu + "_" + dianpu;
                string strData = "";
                foreach (JObject i in jo["data"]["searchResult"])
                {
                    strData += i["id"] + "," + i["title"] + "," + i["backCateName"] + "," + i["address"] + "," + i["areaname"] + "," + i["imageUrl"] + "\n";

                }
                if (strData == "")
                {
                    Console.WriteLine("完毕");
                    return;
                }
                Excel.WriteToCSV(config["dataPath"], fileName, strData);
                Random rd = new Random();
                int num = rd.Next(int.Parse(config["timeMin"]), int.Parse(config["timeMax"]));
                
                Console.WriteLine(strData);
                Console.WriteLine(offset);
                Console.WriteLine("等待" + num + "后");
                System.Threading.Thread.Sleep(num * 1000);
                offset += limit;
            }
        }*/

        /*public static void GetDianpuByHtml(string url)
        {
            string html = Request.HttpGet(url);
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='common-list-main']");
            Console.WriteLine(node);
            return;
        }*/
        static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }

        public static string HttpGet(string url, string referer = "", bool IsProxy = false)
        {
            if (IsProxy)
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
            }
            //创建
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); 
            //设置请求方法
            httpWebRequest.Method = "GET";
            //请求超时时间
            httpWebRequest.Timeout = 20000;
            //设置UA
            httpWebRequest.UserAgent = RandomUserAgent();
            Console.WriteLine(httpWebRequest.UserAgent);
            //设置代理
            if (IsProxy)
            {
                RebuildRequest(httpWebRequest);
            }
            if (referer != "")
            {
                //设置Referer
                httpWebRequest.Referer = Uri.EscapeUriString(referer);
            }
            //发送请求
            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                //利用Stream流读取返回数据
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                //获得最终数据，一般是json
                string responseContent = streamReader.ReadToEnd();
                streamReader.Close();
                httpWebResponse.Close();
                return responseContent;
            }
            catch (Exception ex)
            {
                String str = "";
                str += ex.Message + "\n";//异常消息
                str += ex.StackTrace + "\n";//提示出错位置，不会定位到方法内部去
                //str += ex.ToString() + "\n";//将方法内部和外部所有出错的位置提示出来
                Console.WriteLine(str);
                return null;
            }
            
        }

        public static string HttpPost(string url, string data)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //字符串转换为字节码
            byte[] bs = Encoding.UTF8.GetBytes(data);
            //参数类型，这里是json类型
            httpWebRequest.ContentType = "application/json";
            //参数数据长度
            httpWebRequest.ContentLength = bs.Length;
            //设置请求类型
            httpWebRequest.Method = "POST";
            //设置超时时间
            httpWebRequest.Timeout = 20000;
            //设置UA
            httpWebRequest.UserAgent = RandomUserAgent();
            //将参数写入请求地址中
            httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
            //发送请求
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //读取返回数据
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string responseContent = streamReader.ReadToEnd();
            streamReader.Close();
            httpWebResponse.Close();
            httpWebRequest.Abort();
            return responseContent;
        }

        /// <summary>
        /// 不做catch处理，需要在外部做
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method">默认GET，空则补充为GET</param>
        /// <param name="contenttype">默认json，空则补充为json</param>
        /// <param name="header">请求头部</param>
        /// <param name="data">请求body内容</param>
        /// <returns></returns>
        public static string Http(string url, Hashtable header = null, string method = "GET", string data = null, string contenttype = "application/json;charset=utf-8")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = string.IsNullOrEmpty(method) ? "GET" : method;
            request.ContentType = string.IsNullOrEmpty(contenttype) ? "application/json;charset=utf-8" : contenttype;
            if (header != null)
            {
                foreach (var i in header.Keys)
                {
                    Console.WriteLine(i.ToString());
                    Console.WriteLine(header[i].ToString());
                    request.Headers.Add(i.ToString(), header[i].ToString());
                }
            }
            if (!string.IsNullOrEmpty(data))
            {
                Stream RequestStream = request.GetRequestStream();
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                RequestStream.Write(bytes, 0, bytes.Length);
                RequestStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream ResponseStream = response.GetResponseStream();
            StreamReader StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8"));
            string re = StreamReader.ReadToEnd();
            StreamReader.Close();
            ResponseStream.Close();
            return re;
        }

        public static string TempPath(string str)
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bytes = Encoding.Default.GetBytes(str);//将要加密的字符串转换为字节数组
            byte[] encryptdata = md5.ComputeHash(bytes);//将字符串加密后也转换为字符数组
            string tempFile = Convert.ToBase64String(encryptdata);
            string tempPath = Path.GetTempPath() + tempFile;
            return tempPath;
        }

        public static string GetUuid()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string time = Convert.ToInt64(ts.TotalSeconds).ToString();
            string randmData = Guid.NewGuid().ToString().Substring(24, 12) + Guid.NewGuid().ToString().Substring(24, 8);
            string uuid = $"{randmData}.{time}.1.0.0";
            return uuid;
        }

        private static void RebuildRequest(HttpWebRequest request)
        {
            if (null == request) return;

            if (null == request.Headers) request.Headers = new WebHeaderCollection();

            string appKey = "RFFCSHlUN05BYURLd0xNcjowQTd6bUVtS3VjVlFnR1ps";   // 购买获得的appKey（个人中心页面的隧道订单可以查看）
            string authHeaderName = "Authorization";    // Header名字
            //WebProxy proxy = new WebProxy("transfer.mogumiao.com", 9001); // 代理服务器位置
            WebProxy proxy = new WebProxy("secondtransfer.moguproxy.com", 9001);

            //  为请求头加入authHeader信息
            request.Headers.Add(authHeaderName, "Basic " + appKey);

            //  为请求设置代理服务器信息
            request.Proxy = proxy;
        }

        private static string RandomUserAgent()
        {
            string[] userAgent = new string[] {
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",

                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
                "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
                "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
                "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
                "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",

                "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
                "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
                "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
                "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
                "Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 ",
                "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3",

                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.14) Gecko/20110218 AlexaToolbar/alxf-2.0 Firefox/3.6.14",
                "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
                "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
                "Opera/9.80 (Android 2.3.4; Linux; Opera mobi/adr-1107051709; U; zh-cn) Presto/2.8.149 Version/11.10",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
                "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5",
                "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0",

                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
                "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
            };
            Random rm = new Random();
            int i = rm.Next(userAgent.Length);
            return userAgent[i];
        }
    }
}
